<template>
  <div class="workCenter_detail  form_detail_page">
    <one-title :title="$route.query.id ? '工作中心详情' : '工作中心新增'" @refreshData="refresh"></one-title>
    <div v-loading="isLoading" class="fixed_top_56">
      <el-form ref="listForm" @submit.native.prevent :model="detailData" :rules="rules" v-if="!isEmpty&&!isLoading">
        <two-title title="基本信息"></two-title>
        <div class="from_panel">
          <div class="form_col">
            <el-form-item class="form_item" label="工厂名称:" prop="factoryId">
              <div class="input_wapper">
                <el-select
                  filterable
                  disabled
                  placeholder=""
                  size="small"
                  v-model="detailData.factoryId">
                  <el-option
                    v-for="item in treeList"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="车间名称:" prop="workshopId">
              <div class="input_wapper">
                <el-select
                  filterable
                  placeholder=""
                  size="small"
                  :disabled="isDetail"
                  @change="workshopSelect"
                  v-model="detailData.workshopId">
                  <el-option
                    v-for="item in workshop"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="班组名称:" prop="workgroupId">
              <div class="input_wapper">
                <el-select
                  filterable
                  :disabled="isDetail"
                  v-model="detailData.workgroupId"
                  size="small"
                  @change="selectWorkgroup"
                  placeholder="请选择班组名称">
                  <el-option
                    v-for="item in workgroup"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </div>
          <div class="form_col">
            <el-form-item class="form_item" label="工作中心编号:" prop="number">
              <div class="input_wapper">
                <el-input
                  placeholder="请输入工作中心编号"
                  :disabled="isDetail"
                  v-model.trim="detailData.number"
                  size="small"
                  clearable>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="工作中心名称:" prop="name">
              <div class="input_wapper">
                <el-input
                  placeholder="请输入工作中心名称"
                  v-model.trim="detailData.name"
                  size="small"
                  clearable>
                </el-input>
              </div>
            </el-form-item>
          </div>
        </div>
        <two-title title="其他信息"></two-title>
        <div class="from_panel">
          <div class="form_col">
            <el-form-item class="form_item is-required" label="设备选择:" prop="deviceIdsList">
              <div class="input_wapper">
                <el-select
                  multiple
                  :multiple-limit="100"
                  placeholder="请选择设备"
                  filterable
                  size="small"
                  v-model="detailData.deviceIdsList"
                  @change="multipleChange">
                  <el-option
                    v-for="item in deviceIds"
                    :disabled="deviceIsDisabled(item)"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item is-required" label="人员选择:" prop="staffIdsList">
              <div class="input_wapper">
                <el-select
                  multiple
                  :multiple-limit="100"
                  placeholder="请选择人员"
                  filterable
                  size="small"
                  v-model="detailData.staffIdsList"
                  @change="multipleChange">
                  <el-option
                    v-for="item in staffIds"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item is-required" label="工序选择:" prop="workstageIdsList">
              <div class="input_wapper">
                <el-select
                  multiple
                  :multiple-limit="100"
                  v-model="detailData.workstageIdsList"
                  filterable
                  size="small"
                  placeholder="请选择工序"
                  @change="multipleChange">
                  <el-option
                    v-for="item in workstageIds"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <div class="form_item">
              <label></label>
              <div class="input_wapper mes_btn">
                <el-button type="primary" native-type="submit" @click="save">保存</el-button>
                <el-button @click="cancel">取消</el-button>
              </div>
            </div>
          </div>
          <div class="form_col">
            <el-form-item class="form_item" label="备注:" prop="remarks">
              <div class="input_wapper text_area">
                <el-input type="textarea"
                          :autosize="{ minRows: 2, maxRows: 4}"
                          placeholder="请输入内容"
                          v-model="detailData.remarks"
                          maxlength="255"></el-input>
                <span class="text_length">{{detailData.remarks ? detailData.remarks.length : 0}}/255</span>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <empty-page v-if="isEmpty&&!isLoading"></empty-page>
    </div>
  </div>
</template>

<script>
import TwoTitle from '@/components/TwoTitle'
import EmptyPage from '@/components/EmptyPage'
const initDetail = {
  factoryId: '',
  workshopId: '',
  workgroupId: '',
  deviceIds: '',
  staffIds: '',
  workstageIds: '',
  deviceIdsList: [],
  staffIdsList: [],
  workstageIdsList: [],
  deviceNames: '',
  staffNames: '',
  workstageNames: '',
  workgroupName: ''
}
export default {
  name: 'workCenterDetail',
  components: {
    TwoTitle,
    EmptyPage
  },
  data() {
    return {
      isLoading: true, // 数据加载中
      isEmpty: false, // 是否为空数据
      startWatch: false, // 是否开始监听页面数据变化 统一
      treeList: [], // 树形列表
      // 验证规则
      rules: {
        factoryId: [
          {required: true, message: '请选择工厂', trigger: 'blur'}
        ],
        workshopId: [
          {required: true, message: '请选择车间', trigger: 'blur'}
        ],
        workgroupId: [
          {required: true, message: '请选择班组', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入工作中心名称', trigger: 'blur'},
        ],
        number: [
          {required: true, message: '请输入工作中心编号', trigger: 'blur'},
        ],
        deviceIdsList: [
          {validator: this.isRequired, message: '请选择设备', trigger: 'change'}
        ],
        staffIdsList: [
          {validator: this.isRequired, message: '请选择人员', trigger: 'change'}
        ],
        workstageIdsList: [
          {validator: this.isRequired, message: '请选择工序', trigger: 'change'}
        ]
      },
      // 保存按钮是否点击
      hasClick: false,
      // 详情数据(工作中心详情页面有多选下拉框数据处理和表单验证比较例外，故未使用vuex托管detailData)
      detailData: {},
    }
  },
  computed: {
    // 详情数据
    /*detailData() {
      return this.$store.state.workCenter.detailData
    },*/
    // 工厂id
    factoryId() {
      return this.$store.state.userInfo.factoryId || ''
    },
    // 车间id
    workshopId() {
      return this.$store.state.userInfo.workshopId || ''
    },
    // 车间下拉选择列表
    workshop() {
      if (this.treeList.length > 0 && this.detailData.factoryId) {
        return this.parseData(this.treeList, this.detailData.factoryId, 'workshops')
      } else {
        return []
      }
    },
    // 班组下拉选择列表
    workgroup() {
      if (this.workshop.length > 0 && this.detailData.workshopId) {
        return this.parseData(this.workshop, this.detailData.workshopId, 'workgroups')
      } else {
        return []
      }
    },
    // 设备下拉选择列表
    deviceIds() {
      if (this.workshop.length > 0 && this.detailData.workshopId) {
        let deviceList = this.parseData(this.workshop, this.detailData.workshopId, 'propertys')
        if (this.detailData.deviceIds) {
          return deviceList.filter((item) => !(this.deviceIsDisabled(item) && this.detailData.deviceIds.indexOf(item.id) === -1))
        } else {
          return deviceList.filter((item) => !this.deviceIsDisabled(item))
        }
      } else {
        return []
      }
    },
    // 工序下拉选择列表
    workstageIds() {
      if (this.workshop.length > 0 && this.detailData.workshopId) {
        return this.parseData(this.workshop, this.detailData.workshopId, 'repositorys')
      } else {
        return []
      }
    },
    // 人员下拉选择列表
    staffIds() {
      if (this.workgroup.length > 0 && this.detailData.workgroupId) {
        return this.parseData(this.workgroup, this.detailData.workgroupId, 'staffs')
      } else {
        return []
      }
    },
    saveState() {
      return this.$store.state.saveState
    },
    // 是否是详情页面
    isDetail() {
      return !!this.$route.query.id
    }
  },
  mounted() {
    this.refresh()
    this.initDetailData()
  },
  methods: {
    // 初始detail
    initDetailData() {
      this.detailData = JSON.parse(JSON.stringify(initDetail))
    },
    // 初始化详情页面
    refresh() {
      this.isLoading = true
      this.startWatch = false
      Promise.all([this.getDetail(), this.getTreeList()]).then(() => {
        this.isLoading = false
        this.setBaseInput()
      }).catch(() => {
        this.isLoading = false
      })
    },
    // 工厂、车间赋值
    setBaseInput() {
      this.$nextTick(() => {
        if (!this.$route.query.id) {
          this.$set(this.detailData, 'factoryId', this.factoryId)
          this.$set(this.detailData, 'workshopId', this.workshopId)
        }
        setTimeout(() => {
          this.startWatch = true
        }, 300)
      })
    },
    // 下拉是否已选
    isRequired(rule, num, callback) {
      if (this.hasClick) {
        if (!Array.isArray(num) || (Array.isArray(num) && num.length === 0)) {
          callback(new Error(rule.message))
        } else {
          callback()
        }
      }
    },
    /**
     * 初始化——详情数据
     * @param id 详情id
     * @param postData 请求数据
     */
    getDetail() {
      let id = this.$route.query.id
      let postData = {
        method: 'get',
        url: 'a/workcenter/workcenter/get2/' + id,
        noCommit: true
      }
      if (!id) {
        this.initDetailData()
        return Promise.resolve(true)
      }
      return this.$store.dispatch('saveData', postData).then((res) => {
        if (res) {
          const data = res.data
          this.detailData = data
          // 解析设备、人员、工序字符串成数组
          if (data.useDeviceIds) { this.$set(this.detailData, 'deviceIdsList', data.useDeviceIds.split(',')) }
          if (data.useStaffIds) { this.$set(this.detailData, 'staffIdsList', data.useStaffIds.split(',')) }
          if (data.workstageIds) { this.$set(this.detailData, 'workstageIdsList', data.workstageIds.split(',')) }
        }
        if (id && !res) { this.isEmpty = true }
      }).catch(() => {
        this.isEmpty = true
      })
    },
    /**
     * 初始化——树形结构数据
     */
    getTreeList() {
      return this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workcenter/workcenter/getNameTree',
        module: 'workCenter',
        state: 'treeList'
      }).then((res) => {
        this.treeList = res[0].workshopData || []
      }).catch(() => {
        this.tipMessage('error', '基础数据加载失败请重新加载页面')
      })
    },
    /**
     * 解析树形子集，如选择工厂时获取所选工厂下的车间列表
     * @param {Array} list 父集列表
     * @param {String} id 所选父集元素id
     * @param {Array} field 表示子集的字段名称，如：workshops（车间）
     * @returns {Array}
     */
    parseData(list, id, field) {
      let result = list.find(value => value.id === id)
      return result ? list.find(value => value.id === id)[field] || [] : []
    },
    // device设备报废禁用
    deviceIsDisabled(item) {
      return item['text'].indexOf('已报废') > -1
    },
    /**
     * 选择车间并重置班组列表
     */
    workshopSelect () {
      this.detailData.workgroupId = ''
      this.$set(this.detailData, 'deviceIdsList', [])
      this.$set(this.detailData, 'workstageIdsList', [])
      this.$set(this.detailData, 'staffIdsList', [])
    },
    /**
     * 选择班组，并重置相关子集
     */
    selectWorkgroup() {
      this.detailData.workgroupName = this.getNameList([this.detailData.workgroupId], this.workgroup)
      this.$set(this.detailData, 'staffIdsList', [])
    },
    /**
     * 多选设备、人员、工序事件
     */
    multipleChange() {
      this.multSelectCollect()
      if (this.startWatch) {
        this.$store.commit('SetHasDetailChange', true)
      } else {
        this.$store.commit('SetHasDetailChange', false)
      }
    },
    /**
     * 获取详情人员、设备、工序名称
     * @param ids 下拉选择框所选id list
     * @param treeList 下拉选择框选项 list
     */
    getNameList(ids, treeList) {
      let result = []
      ids.forEach((item) => {
        let obj = treeList.find((value) => item === value.id)
        if (obj) result.push(obj.text)
      })
      return result.join(',')
    },
    // 多选下拉框数据处理
    multSelectCollect() {
      // 拼接设备、人员、工序字符串
      this.detailData.deviceIds = this.detailData.deviceIdsList.join(',')
      this.detailData.deviceNames = this.getNameList(this.detailData.deviceIdsList, this.deviceIds)
      // 拼接设备、人员、工序字符串
      this.detailData.staffIds = this.detailData.staffIdsList.join(',')
      this.detailData.staffNames = this.getNameList(this.detailData.staffIdsList, this.staffIds)
      // 拼接设备、人员、工序字符串
      this.detailData.workstageIds = this.detailData.workstageIdsList.join(',')
      this.detailData.workstageNames = this.getNameList(this.detailData.workstageIdsList, this.workstageIds)
    },
    /**
     * 保存数据
     */
    save() {
      this.hasClick = true
      this.multSelectCollect()
      if (this.saveState === true) return
      this.$refs['listForm'].validate((valid) => {
        if (valid) {
          this.$store.commit('SetSaveState', true)
          this.saveData()
        }
      })
    },
    // 保存数据
    saveData() {
      const details = JSON.parse(JSON.stringify(this.detailData))
      delete details.deviceIdsList
      delete details.staffIdsList
      delete details.workstageIdsList
      let postData = {
        method: 'post',
        url: 'a/workcenter/workcenter/save2',
        module: 'workCenter',
        data: details,
        noCommit: true
      }
      this.$store.dispatch('saveData', postData).then(() => {
        this.saveSuccess()
      }).catch(() => {
        this.$store.commit('SetSaveState', false)
      })
    },
    // 保存成功回调
    saveSuccess() {
      this.$message.success({
        message: '保存成功',
        duration: 500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false) // 保存成功时需要将页面变化标记重置回false
          this.$store.dispatch('delCurrentViews', this.$route).then(() => {
            this.$store.commit('SetSaveState', false)
            this.$router.push('/workCenter')
            this.$store.commit('SetRefresh', true)
          })
        }
      })
    },
    /**
     * 取消并关闭页面
     */
    cancel() {
      this.backToList().then(() => {
        this.$store.dispatch('delCurrentViews', this.$route).then(() => {
          this.$router.push('/workCenter')
        }
        )
      })
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  },
  watch: {
    detailData: {
      // 当前页面数据变化总是会被监听到，我们只需要在我们想要开始监听startWatch的时候判断当前页面是否有变化
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        } else {
          this.$store.commit('SetHasDetailChange', false)
        }
      },
      deep: true
    },
    factoryId: {
      handler() {
        this.setBaseInput()
      },
      deep: true
    }
  }
}
</script>

<style lang="less">
  .el-select-dropdown__item.is-disabled{
    color: #c0c4cc!important;
    font-weight: normal!important;
  }
  .el-tag--small {
    height: 22px;
    .el-tag__close.el-icon-close {
      top: -1px;
    }
  }
</style>
